package com.example.module.ai.tencent.http;

import com.example.module.ai.config.TencentAppProperties;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class TencentAppHttpSSEService {

    @Resource
    private TencentAppProperties tencentAppProperties;

    private static final String sseUrl = "https://wss.lke.cloud.tencent.com/v1/qbot/chat/sse"; // SSE 服务器的 URL
    private static final String visitorBizId = "202403180001"; //   访客 ID（外部系统提供，需确认不同的访客使用不同的 ID）

    @SneakyThrows
    public void sseInvoke(String content, String sid) {

        // 创建 OkHttpClient 对象
        OkHttpClient client = new OkHttpClient();

        // 创建 JSON 请求体
        MediaType mediaType = MediaType.get("application/json");
        JSONObject reqBody = new JSONObject();
        reqBody.put("content", content);
        reqBody.put("bot_app_key", tencentAppProperties.getBotAppkey());
        reqBody.put("visitor_biz_id", visitorBizId);
        reqBody.put("session_id", sid);

        Request request = new Request.Builder()
                .url(sseUrl)
                .post(RequestBody.create(reqBody.toString(), mediaType))
                .build();

        EventSourceListener listener = new EventSourceListener() {
            @Override
            public void onOpen(@NotNull EventSource eventSource, @NotNull Response response) {
                log.info("SSE connection opened");
            }

            @Override
            public void onClosed(@NotNull EventSource eventSource) {
                log.info("SSE connection closed");
            }

            @Override
            public void onEvent(@NotNull EventSource eventSource, String id, String type, @NotNull String data) {
                if ("reply".equals(type)) {
                    try {
                        JSONObject dataObj = new JSONObject(data);
                        JSONObject payload = dataObj.getJSONObject("payload");
                        if (payload.length() > 0) {
                            boolean isFromSelf = payload.getBoolean("is_from_self");
                            boolean isFinal = payload.getBoolean("is_final");
                            String content = payload.getString("content");
                            if (isFromSelf) {
                                System.out.println("is_from_self, event: " + type + ", content: " + content);
                            } else if (isFinal) {
                                System.out.println("is_final, event: " + type + ", content: " + content);
                            }
                        }
//                    System.out.println("Received SSE reply: " + dataObj);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    log.info("Received SSE event: {}", type);
                }

            }

            @Override
            public void onFailure(@NotNull EventSource eventSource, Throwable t, Response response) {
                log.error("Error occurred: {}", t.getMessage());
            }
        };
        EventSource.Factory factory = EventSources.createFactory(client);
        factory.newEventSource(request, listener);
    }

}